package cn.yjh.utils;

import java.lang.reflect.Field;
import java.nio.Buffer;
import java.nio.ByteBuffer;

/**
 * @author yW0041229
 * @since 2022/1/7 15:52
 */
public class ByteBufferUtils {


    /**
     * 将 startOffset - endOffset 区间的数据，复制到 ByteBuffer 的最前面
     * @param buffer
     * @param startOffset
     * @param endOffset
     */
    public static void resetByteBuffer(ByteBuffer buffer,int startOffset, int endOffset){
        byte[] array = buffer.array();
        int len = endOffset-startOffset;
        System.arraycopy(array, startOffset, array, 0, len);
        buffer.position(len);
        buffer.limit(buffer.capacity());
    }

    public static void expandByteBufferCapacity(ByteBuffer buffer,int multiple){
        byte[] array = buffer.array();
        int capacity = buffer.capacity();
        int newCapacity = capacity * multiple;
        byte[] hb = new byte[newCapacity];
        System.arraycopy(array, 0, hb, 0, capacity);
        //buffer.position(capacity);
        modifyField(buffer,"java.nio.Buffer", "capacity", newCapacity);
        buffer.limit(newCapacity);
        modifyField(buffer,"java.nio.ByteBuffer","hb",hb);
        //modifyField(buffer,"java.nio.Buffer","mark",-1);

    }

    /**
     * 反射修改 ByteBuffer 的属性值
     * @param buffer
     * @param fieldName
     * @param index
     */
    public static void modifyField(ByteBuffer buffer,String className, String fieldName, Object index){
        try {
            Class<?> clazz = Class.forName(className);
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(buffer,index);
        } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

}
